import Vue from "vue";
import VueRouter from "vue-router";
import routes from './routes'

// 使用插件
Vue.use(VueRouter);

import store from '@/store'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 配置路由
let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  },
})
// 前置守卫，在路由跳转之前判断
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token;
  let name = store.state.user.info.loginName;
  if (token) {
    if (to.path == '/login') {
      next('/home');
    } else {
      if (name) {
        next();
      } else {
        try {
          store.dispatch('getUserInfo')
          next()
        } catch (error) {
          await store.dispatch('userLogout')
          next('/login')
        }
      }
    }
  } else {
    next();
  }
})



export default router;
